/* eslint-disable consistent-return */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { DownOutlined, PlusOutlined, UpOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
  Row,
  Col,
  Card,
  Button,
  Dropdown,
  Menu,
  Modal,
  message,
  Badge,
  Divider,
  Tabs,
  DatePicker,
  Alert,
  Select,
} from 'antd';
import router from 'umi/router';
import moment from 'moment';
import queryString from 'query-string';
import StandardTable from '@/components/StandardTable';
import Authorized from '@/utils/Authorized';
import { checkPermissions } from '@/utils/authority';
import styles from '@/utils/utils.less';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import HOCSelect from '@/components/AntDesign/Select';
import Customer from '../../components/Customer';
import Contract from '../../components/Contract';
import SuppContract from '../../components/SuppCont';
import Supplier from '../../components/Supplier';
import DictCode from '../../components/DictCode';
import TextOverFlow from '../../components/TextOverFlow';

const FormItem = Form.Item;
const { TabPane } = Tabs;
const { RangePicker } = DatePicker;
const { Option } = Select;

@connect(({ publicdata, busicont, loading }) => ({
  dictCode: publicdata.dictCode,
  pageData: busicont.pageData,
  loading: loading.models.busicont,
  tabList: busicont.tabList,
  stateMap: busicont.stateMap,
  expandForm: busicont.expandForm,
  activeKey: busicont.activeKey,
  formFieldsValue: busicont.formFieldsValue,
  valuesArr: busicont.valuesArr,
  respUserList: busicont.respUserList,
}))
@Form.create()
class TableList extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      selectedRows: [],
      selectedRowKeys: [],
      renewalContNum: 0,
      contStateList: [],
    };

    this.tableSearchLayout = {
      labelCol: { md: { span: 7 } },
      wrapperCol: { md: { span: 15 } },
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'publicdata/fetchDictCode',
      payload: ['CUSTCONT_STATUS'],
      callback: data => {
        this.setState({ contStateList: data.CUSTCONT_STATUS });
      },
    });
    dispatch({
      type: 'busicont/fetchRenewalContNum',
      payload: {
        custId: null,
        contId: null,
        contState: '0',
        contNo: null,
        serType: null,
        beginDate: null,
        endDate: null,
        creTime: null,
        pageArg: { currentPage: 1, pageSize: 10 },
      },
      callback: data => {
        if (data.totalCount) {
          this.setState({ renewalContNum: data.totalCount });
        }
      },
    });
    // 获取所属客服列表数据
    dispatch({
      type: 'busicont/fetchRespUserList',
      payload: {},
    });
    this.getInitialList();
  }

  getInitialList = () => {
    const {
      pageData: { pagination },
      dispatch,
      location,
      formFieldsValue,
      activeKey,
    } = this.props;
    const tempActiveKey = queryString.parse(location.search).activeKey || activeKey;
    if (location.queryParam) {
      dispatch({
        type: 'busicont/updateModalData',
        payload: { formFieldsValue: location.queryParam, expandForm: true },
      });
    }
    dispatch({
      type: 'busicont/updateModalData',
      payload: {
        activeKey: tempActiveKey,
      },
    });
    this.searchList(
      this.processFormData({ ...formFieldsValue, ...location.queryParam }),
      tempActiveKey,
      pagination.current,
      pagination.pageSize
    );
  };

  // 点击查询按钮
  searchBtnList = activeKey => {
    const { form, valuesArr, dispatch } = this.props;
    form.validateFieldsAndScroll([...valuesArr], (err, values) => {
      if (!err) {
        dispatch({
          type: 'busicont/updateModalData',
          payload: {
            activeKey,
            formFieldsValue: values,
          },
        });
        this.searchList(this.processFormData(values), activeKey);
      }
    });
  };

  // 查询
  searchList = (
    formFieldsValue,
    activeKey = '1',
    currentPage = 1,
    pageSize = 10,
    isClear = true
  ) => {
    if (isClear) {
      this.setState({ selectedRows: [], selectedRowKeys: [] });
    }
    const { dispatch } = this.props;
    const pageArg = { currentPage, pageSize };
    const values = {
      ...formFieldsValue,
      pageArg,
    };

    dispatch({
      type: 'busicont/updateModalData',
      payload: {
        values,
      },
    });

    if (activeKey === '1') {
      dispatch({
        type: 'busicont/fetchCustContList',
        payload: {
          ...values,
        },
      });
    } else {
      dispatch({
        type: 'busicont/fetchSuppContList',
        payload: values,
      });
    }
  };

  // 处理form数据
  processFormData = fieldsValue => {
    const { activeKey } = this.props;
    const formFieldsValue = {};
    const tempFieldsValue = fieldsValue;
    Object.keys(tempFieldsValue).forEach(key => {
      if (key === 'creTime') {
        formFieldsValue.beginDate = tempFieldsValue.creTime
          ? tempFieldsValue.creTime[0].format('YYYY-MM-DD')
          : null;
        formFieldsValue.endDate = tempFieldsValue.creTime
          ? tempFieldsValue.creTime[1].format('YYYY-MM-DD')
          : null;
      }
      formFieldsValue[key] = tempFieldsValue[key] === undefined ? null : tempFieldsValue[key];
      delete formFieldsValue.creTime;
    });
    if (activeKey === '2') {
      formFieldsValue.contId = formFieldsValue.suppContId;
      delete formFieldsValue.suppContId;
    }
    return formFieldsValue;
  };

  // 切换表格展开收起
  toggleForm = () => {
    const { dispatch, expandForm } = this.props;
    dispatch({
      type: 'busicont/updateModalData',
      payload: {
        expandForm: !expandForm,
      },
    });
  };

  // 点击复选框
  handleSelectRows = (selectedRows, selectedRowKeys) => {
    this.setState({ selectedRows, selectedRowKeys });
  };

  // 表格有变化：比如：切换页码
  handleStandardTableChange = pagination => {
    const { activeKey, formFieldsValue } = this.props;
    this.searchList(
      this.processFormData(formFieldsValue),
      activeKey,
      pagination.current,
      pagination.pageSize,
      false
    );
  };

  // 重置
  resetSearch = () => {
    const { form, dispatch } = this.props;
    dispatch({
      type: 'busicont/updateModalData',
      payload: {
        formFieldsValue: {},
      },
    });
    form.resetFields();
    form.setFieldsValue({ creTime: null });
  };

  // 切换页签
  changeTabPane = activeKey => {
    let { contStateList } = this.state;
    const { dictCode, dispatch, formFieldsValue } = this.props;
    this.resetSearch();
    router.push({
      pathname: '/salemanage/busicont/index',
      query: {
        activeKey,
      },
    });
    dispatch({
      type: 'busicont/updateModalData',
      payload: {
        activeKey,
        formFieldsValue: {
          ...formFieldsValue,
        },
      },
    });
    if (activeKey === '2') {
      contStateList = dictCode.CUSTCONT_STATUS.filter(item => item.itemCode !== '0');
    } else {
      contStateList = dictCode.CUSTCONT_STATUS;
    }
    this.setState({ selectedRows: [], selectedRowKeys: [], contStateList }, () => {
      this.searchList(this.processFormData(formFieldsValue), activeKey);
    });
  };

  // 添加报价单
  addQuo = () => {
    const { selectedRowKeys, selectedRows } = this.state;
    if (selectedRowKeys.length === 0) {
      message.warning('请选择一条数据!');
    } else if (selectedRowKeys.length === 1) {
      if (selectedRows[0].contState === 0) {
        return message.warning('待续签合同不允许添加报价单，请重新选择!');
      }
      if (selectedRows[0].contState === 3) {
        return message.warning('此合同已停用，无法添加报价单，可启用之后再添加！');
      }
      // custId: 客户合同   suppId:供应商合同
      // 是本地客户合同还是全国供应商合同
      const contInfo = selectedRows[0];
      if (contInfo.custId) {
        router.push(
          encodeURI(
            `/salemanage/quotation/add?comType=${1}&custId=${contInfo.custId}&custName=${
              contInfo.custName
            }&contId=${contInfo.contId}&contName=${contInfo.contName}&serType=${contInfo.serType}`
          )
        );
      } else {
        router.push(
          encodeURI(
            `/salemanage/quotation/add?comType=${2}&suppId=${contInfo.suppId}&contId=${
              contInfo.contId
            }`
          )
        );
      }
    } else {
      message.warning('只能选择一条数据！');
    }
  };

  // 更新状态
  updateStatus = (contState, contId, record) => {
    const {
      dispatch,
      pageData: {
        pagination: { current, pageSize },
      },
      activeKey,
      formFieldsValue,
    } = this.props;
    this.handleSelectRows([record], [contId]);
    const status = contState === 2 || contState === 0 ? 3 : 2;
    Modal.confirm({
      icon: <QuestionCircleOutlined />,
      title: `你确定要${contState === 2 || contState === 0 ? '停用' : '启用'}"${
        record.contName
      }"合同吗？`,
      okText: '确定',
      okType: 'primary',
      cancelText: '取消',
      style: { top: 200 },
      onOk: () => {
        dispatch({
          type: 'busicont/updateStatus',
          url: activeKey === '1' ? '/csApi/custCont/updateState' : '/csApi/suppCont/updateState',
          payload: { contId, contState: status },
          callback: res => {
            if (res.success) {
              this.searchList(this.processFormData(formFieldsValue), activeKey, current, pageSize);
              this.setState({ selectedRowKeys: [] });
              message.success(`${status === 2 ? '启用成功！' : '停用成功！'}`);
            } else {
              message.warning(res.message || `${status === 2 ? res.message || '启用失败！' : '停用失败！'}`);
            }
          },
        });
      },
      onCancel: () => {
        this.setState({ selectedRowKeys: [] });
      },
    });
  };

  // 查看详情
  toDetail = contId => {
    const { activeKey } = this.props;
    if (activeKey === '2') {
      router.push(`/salemanage/busicont/supplycondetail?activeKey=1&contId=${contId}`);
    } else {
      router.push(`/salemanage/busicont/detail?activeKey=${activeKey}&contId=${contId}`);
    }
  };

  // 修改信息
  update = (contState, contId) => {
    const { activeKey } = this.props;
    if (activeKey === '2') {
      router.push(
        `/salemanage/busicont/supplyupdate?activeKey=${activeKey}&contId=${contId}&contState=${contState}`
      );
    } else {
      router.push(
        `/salemanage/busicont/update?activeKey=${activeKey}&contId=${contId}&contState=${contState}`
      );
    }
  };

  // 删除数据
  delete = (contId, record) => {
    const {
      dispatch,
      pageData: {
        pagination: { current, pageSize, total },
      },
      activeKey,
      formFieldsValue,
    } = this.props;
    this.handleSelectRows([record], [contId]);
    Modal.confirm({
      icon: <QuestionCircleOutlined />,
      title: `你确定要删除"${record.contName}"合同吗？`,
      okText: '确定',
      okType: 'primary',
      cancelText: '取消',
      style: { top: 200 },
      onOk: () => {
        dispatch({
          type: 'busicont/delCont',
          url: activeKey === '1' ? '/csApi/custCont/delete' : '/csApi/suppCont/delete',
          payload: { list: [contId] },
          callback: res => {
            if (res.success) {
              const selectedLen = 1;
              if (current > 1 && (total % pageSize === selectedLen || pageSize === selectedLen)) {
                this.searchList(
                  this.processFormData(formFieldsValue),
                  activeKey,
                  current - 1,
                  pageSize
                );
              } else {
                this.searchList(
                  this.processFormData(formFieldsValue),
                  activeKey,
                  current,
                  pageSize
                );
              }
              this.setState({ selectedRowKeys: [] });
              message.success('删除成功！');
            } else {
              message.warning(`${res.message || '删除失败'}`);
            }
          },
        });
      },
      onCancel: () => {
        this.setState({ selectedRowKeys: [] });
      },
    });
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
      activeKey,
      formFieldsValue,
    } = this.props;
    return (
      <Card style={{ backgroundColor: '#fafafa', padding: '24px 0 0 0' }} bordered={false}>
        <Form layout="inline">
          <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
            <Col md={8} sm={24}>
              {activeKey === '1' ? (
                <FormItem {...this.tableSearchLayout} label="客户名称">
                  {getFieldDecorator('custId', {
                    initialValue: formFieldsValue.custId,
                  })(<Customer allowClear />)}
                </FormItem>
              ) : (
                <FormItem {...this.tableSearchLayout} label="供应商名称">
                  {getFieldDecorator('suppId', {
                    initialValue: formFieldsValue.suppId,
                  })(<Supplier allowClear />)}
                </FormItem>
              )}
            </Col>
            <Col md={8} sm={24}>
              {activeKey === '1' ? (
                <FormItem {...this.tableSearchLayout} label="合同名称">
                  {getFieldDecorator('contId', {
                    initialValue: formFieldsValue.contId,
                  })(<Contract allowClear />)}
                </FormItem>
              ) : (
                <FormItem {...this.tableSearchLayout} label="合同名称">
                  {getFieldDecorator('suppContId', {
                    initialValue: formFieldsValue.suppContId,
                  })(<SuppContract allowClear />)}
                </FormItem>
              )}
            </Col>
            <Col md={8} sm={24}>
              <span className={styles.submitButtons}>
                <Button
                  type="primary"
                  htmlType="submit"
                  onClick={() => this.searchBtnList(activeKey)}
                >
                  查询
                </Button>
                <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                  重置
                </Button>
                <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                  展开 <DownOutlined />
                </a>
              </span>
            </Col>
          </Row>
        </Form>
      </Card>
    );
  }

  renderAdvancedForm() {
    const {
      form: { getFieldDecorator },
      activeKey,
      formFieldsValue,
      respUserList,
    } = this.props;
    const { contStateList } = this.state;
    return (
      <Card style={{ backgroundColor: '#fafafa', padding: '24px 0 0 0' }} bordered={false}>
        <Form layout="inline">
          <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
            <Col md={8} sm={24}>
              {activeKey === '1' ? (
                <FormItem {...this.tableSearchLayout} label="客户名称">
                  {getFieldDecorator('custId', {
                    initialValue: formFieldsValue.custId,
                  })(<Customer allowClear />)}
                </FormItem>
              ) : (
                <FormItem {...this.tableSearchLayout} label="供应商名称">
                  {getFieldDecorator('suppId', {
                    initialValue: formFieldsValue.suppId,
                  })(<Supplier allowClear />)}
                </FormItem>
              )}
            </Col>
            <Col md={8} sm={24}>
              {activeKey === '1' ? (
                <FormItem {...this.tableSearchLayout} label="合同名称">
                  {getFieldDecorator('contId', {
                    initialValue: formFieldsValue.contId,
                  })(<Contract allowClear />)}
                </FormItem>
              ) : (
                <FormItem {...this.tableSearchLayout} label="合同名称">
                  {getFieldDecorator('suppContId', {
                    initialValue: formFieldsValue.suppContId,
                  })(<SuppContract allowClear />)}
                </FormItem>
              )}
            </Col>
            <Col md={8} sm={24}>
              <FormItem {...this.tableSearchLayout} label="合同状态">
                {getFieldDecorator('contState', {
                  initialValue: formFieldsValue.contState,
                })(
                  <Select placeholder="请选择" allowClear>
                    {contStateList.map(item => (
                      <Option key={item.itemCode}>{item.itemName}</Option>
                    ))}
                  </Select>
                )}
              </FormItem>
            </Col>
          </Row>
          <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
            {activeKey === '1' ? (
              <Col md={8} sm={24}>
                <FormItem {...this.tableSearchLayout} label="服务类型">
                  {getFieldDecorator('serType', {
                    initialValue: formFieldsValue.serType,
                  })(<DictCode dictType="SER_TYPE" allowClear />)}
                </FormItem>
              </Col>
            ) : null}
            <Col md={8} sm={24}>
              <FormItem {...this.tableSearchLayout} label="创建日期">
                {getFieldDecorator('creTime', {
                  initialValue: formFieldsValue.creTime,
                })(
                  <RangePicker
                    placeholder={['创建开始日期', '创建结束日期']}
                    style={{ width: '100%' }}
                    format="YYYY-MM-DD"
                  />
                )}
              </FormItem>
            </Col>
            <Col md={8} sm={24}>
              <FormItem label="所属客服" {...this.tableSearchLayout}>
                {getFieldDecorator('primId', {
                  rules: [{ required: false, message: '请选择' }],
                  initialValue: formFieldsValue.primId,
                })(
                  <HOCSelect
                    placeholder="请输入关键字检索"
                    style={{ width: '100%' }}
                    showSearch
                    optionFilterProp="children"
                    allowClear
                  >
                    {respUserList.map(item => (
                      <Option key={item.userId} title={item.userName}>
                        {item.userName}
                      </Option>
                    ))}
                  </HOCSelect>
                )}
              </FormItem>
            </Col>
            {activeKey === '1' ? null : (
              <Col md={8} sm={24}>
                <div style={{ overflow: 'hidden' }}>
                  <span style={{ float: 'right', marginBottom: 24, marginRight: 24 }}>
                    <Button type="primary" onClick={() => this.searchBtnList(activeKey)}>
                      查询
                    </Button>
                    <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                      重置
                    </Button>
                    <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                      收起 <UpOutlined />
                    </a>
                  </span>
                </div>
              </Col>
            )}
          </Row>
          <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
            <Col md={8} sm={24} />
            <Col md={8} sm={24} />
            <Col md={8} sm={24}>
              {activeKey === '1' ? (
                <div style={{ overflow: 'hidden' }}>
                  <div style={{ float: 'right', marginBottom: 24, marginRight: 24 }}>
                    <Button
                      type="primary"
                      htmlType="submit"
                      onClick={() => this.searchBtnList(activeKey)}
                    >
                      查询
                    </Button>
                    <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                      重置
                    </Button>
                    <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                      收起
                      <UpOutlined />
                    </a>
                  </div>
                </div>
              ) : null}
            </Col>
          </Row>
        </Form>
      </Card>
    );
  }

  renderForm() {
    const { expandForm } = this.props;
    return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  }

  render() {
    const { pageData, loading, tabList, stateMap, activeKey } = this.props;
    const { selectedRows, selectedRowKeys, renewalContNum } = this.state;
    const operation = (state, contId, record) => {
      switch (state) {
        case 1: // 待启用
          return (
            <span>
              <Authorized
                authority={
                  activeKey === '1' ? 'cs:custCont:updateState' : 'cs:suppCont:updateState'
                }
                noMatch={null}
              >
                <a onClick={() => this.updateStatus(state, contId, record)}>启用</a>
              </Authorized>
              <Divider type="vertical" />
              <Dropdown
                overlay={
                  <Menu>
                    <Menu.Item key="view" onClick={() => this.toDetail(contId)}>
                      查看
                    </Menu.Item>
                    {checkPermissions(
                      activeKey === '1' ? 'cs:custCont:update' : 'cs:suppCont:update'
                    ) && (
                      <Menu.Item key="update" onClick={() => this.update(state, contId)}>
                        修改
                      </Menu.Item>
                    )}
                    {checkPermissions(
                      activeKey === '1' ? 'cs:custCont:delete' : 'cs:suppCont:delete'
                    ) && (
                      <Menu.Item key="delete" onClick={() => this.delete(contId, record)}>
                        删除
                      </Menu.Item>
                    )}
                  </Menu>
                }
              >
                <a>
                  更多
                  <DownOutlined />
                </a>
              </Dropdown>
            </span>
          );
        case 2: // 已启用：停用
          return (
            <span>
              <a onClick={() => this.toDetail(contId)}>查看</a>
              <Divider type="vertical" />
              <Dropdown
                overlay={
                  <Menu>
                    {checkPermissions(
                      activeKey === '1' ? 'cs:custCont:update' : 'cs:suppCont:update'
                    ) && (
                      <Menu.Item key="update" onClick={() => this.update(state, contId)}>
                        修改
                      </Menu.Item>
                    )}
                    {checkPermissions(
                      activeKey === '1' ? 'cs:custCont:updateState' : 'cs:suppCont:updateState'
                    ) && (
                      <Menu.Item
                        key="delete"
                        onClick={() => this.updateStatus(state, contId, record)}
                      >
                        停用
                      </Menu.Item>
                    )}
                  </Menu>
                }
              >
                <a>
                  更多
                  <DownOutlined />
                </a>
              </Dropdown>
            </span>
          );
        case 0: //  待续签：续签
          return (
            <span>
              <Authorized authority="cs:custCont:renew" noMatch={null}>
                <a
                  onClick={() =>
                    router.push(
                      `/salemanage/busicont/renewal?contId=${contId}&activeKey=${activeKey}`
                    )
                  }
                >
                  续签
                </a>
              </Authorized>
              <Divider type="vertical" />
              <Dropdown
                overlay={
                  <Menu>
                    <Menu.Item key="update" onClick={() => this.toDetail(contId)}>
                      查看
                    </Menu.Item>
                    {checkPermissions(
                      activeKey === '1' ? 'cs:custCont:updateState' : 'cs:suppCont:updateState'
                    ) && (
                      <Menu.Item
                        key="delete"
                        onClick={() => this.updateStatus(state, contId, record)}
                      >
                        停用
                      </Menu.Item>
                    )}
                  </Menu>
                }
              >
                <a>
                  更多
                  <DownOutlined />
                </a>
              </Dropdown>
            </span>
          );
        case 3: // 已停用：启用
          return (
            <span>
              <a onClick={() => this.toDetail(contId)}>查看</a>
              <Divider type="vertical" />
              {checkPermissions(
                activeKey === '1' ? 'cs:custCont:updateState' : 'cs:suppCont:updateState'
              ) && <a onClick={() => this.updateStatus(state, contId, record)}>启用</a>}
            </span>
          );
        default:
          return <div />;
      }
    };
    const columns = [
      {
        title: '合同名称',
        dataIndex: 'contName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: (text, record) => {
          if (record.overDue && Number(record.overDue) === 1) {
            // 待续签
            return (
              <div style={{ display: 'flex' }}>
                <TextOverFlow text={text} />
                <span
                  style={{
                    marginLeft: '-10px',
                    border: '1px solid red',
                    width: '64px',
                    color: 'red',
                    borderRadius: '4px',
                    fontSize: '16px',
                    WebkitTextSizeAdjust: 'none',
                    display: 'inline-block',
                    transform: 'scale(0.5)',
                    textAlign: 'center',
                  }}
                >
                  逾期
                </span>
              </div>
            );
          }
          return <TextOverFlow text={text} />;
        },
      },
      {
        title: '客户名称',
        dataIndex: 'custName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: (text, record) => (
          <a onClick={() => router.push(`/salemanage/customer/detail?custId=${record.custId}`)}>
            <TextOverFlow text={text} />
          </a>
        ),
      },
      {
        title: '服务类型',
        dataIndex: 'serTypeName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '合同状态',
        dataIndex: 'contStateName',

        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: (text, record) => (
          <Badge key={record.contState} status={stateMap[record.contState]} text={text} />
        ),
      },
      {
        title: '创建时间',
        dataIndex: 'creTime',
        sorter: (a, b) => new Date(b.creTime) - new Date(a.creTime),
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: val => val && moment(val).format('YYYY-MM-DD HH:mm'),
      },
      {
        title: '所属客服',
        dataIndex: 'primName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: val => (val && val) || '--',
      },
      {
        title: '操作',
        dataIndex: 'operation',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', width: 150, textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: (text, record) => operation(record.contState, record.contId, record),
      },
    ];
    const columnsSupply = [
      {
        title: '合同名称',
        dataIndex: 'contName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '签约方',
        dataIndex: 'suppName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: (text, record) => (
          <a onClick={() => router.push(`/salemanage/supplier/detail?suppId=${record.suppId}`)}>
            <TextOverFlow text={text} />
          </a>
        ),
      },
      {
        title: '合同状态',
        dataIndex: 'contStateName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: (text, record) => (
          <Badge key={record.contState} status={stateMap[record.contState]} text={text} />
        ),
      },
      {
        title: '创建时间',
        dataIndex: 'creTime',
        sorter: (a, b) => new Date(b.creTime) - new Date(a.creTime),
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: val => val && moment(val).format('YYYY-MM-DD HH:mm'),
      },
      {
        title: '所属客服',
        dataIndex: 'primName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '操作',
        dataIndex: 'operation',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', width: 150, textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: (text, record) => operation(record.contState, record.contId, record),
      },
    ];
    const custCont = (
      <div>
        <Row style={{ marginBottom: 16 }}>
          <Authorized authority="cs:custCont:insert" noMatch={null}>
            <Button
              type="primary"
              onClick={() => router.push('/salemanage/busicont/add')}
              style={{ marginRight: 8 }}
            >
              <PlusOutlined />
              新增
            </Button>
          </Authorized>
          <Authorized authority="cs:crmquo:insert" noMatch={null}>
            <Button style={{ marginRight: 8 }} onClick={this.addQuo}>
              添加报价单
            </Button>
          </Authorized>
          <Authorized authority="cs:custCont:uploadCustContOut" noMatch={null}>
            <Button onClick={() => router.push(`/salemanage/busicont/batchAdd`)}>批量新增</Button>
          </Authorized>
        </Row>
        {renewalContNum ? (
          <Alert
            style={{ marginBottom: 16 }}
            message={
              <span>
                您有<span style={{ margin: '0 5px', color: '#faad14' }}>{renewalContNum}</span>
                份待续签合同
              </span>
            }
            type="warning"
            showIcon
          />
        ) : null}
        <StandardTable
          selectedRows={selectedRows}
          selectedRowKeys={selectedRowKeys}
          loading={loading}
          data={pageData}
          rowKey="contId"
          columns={columns}
          onSelectRow={this.handleSelectRows}
          onChange={this.handleStandardTableChange}
        />
      </div>
    );
    const supplyCont = (
      <div>
        <Row style={{ marginBottom: 16 }}>
          <Authorized authority="cs:suppCont:insert" noMatch={null}>
            <Button
              type="primary"
              onClick={() => router.push('/salemanage/busicont/supplyadd')}
              style={{ marginRight: 8 }}
            >
              <PlusOutlined />
              新增
            </Button>
          </Authorized>
          <Authorized authority="cs:crmquo:insert" noMatch={null}>
            <Button style={{ marginRight: 8 }} onClick={this.addQuo}>
              添加报价单
            </Button>
          </Authorized>
          <Authorized authority="cs:custCont:uploadSuppContOut" noMatch={null}>
            <Button onClick={() => router.push(`/salemanage/busicont/supplybatchadd`)}>
              批量新增
            </Button>
          </Authorized>
        </Row>
        <StandardTable
          selectedRows={selectedRows}
          selectedRowKeys={selectedRowKeys}
          loading={loading}
          data={pageData}
          rowKey="contId"
          columns={columnsSupply}
          onSelectRow={this.handleSelectRows}
          onChange={this.handleStandardTableChange}
        />
      </div>
    );
    // 获取页签组件
    const getTabPane = key => {
      switch (key) {
        case '1':
          return custCont;
        case '2':
          return supplyCont;
        default:
          return <div />;
      }
    };
    return (
      <PageHeaderWrapper>
        <Card className={styles.tabCard}>
          <Tabs activeKey={activeKey} onChange={this.changeTabPane}>
            {tabList.map(pane => (
              <TabPane tab={pane.itemName} key={pane.itemCode}>
                <div className={styles.tableListForm}>{this.renderForm()}</div>
                {getTabPane(pane.itemCode)}
              </TabPane>
            ))}
          </Tabs>
        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default TableList;
